# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  #include SimpleCaptcha::ControllerHelpers
  
  helper :all # include all helpers, all the time
  #protect_from_forgery :secret => "fjdksla;fnkfndls;afdsagfdfdsaaaaaaaaaaaaacvc54354354365"
  skip_before_filter :verify_authenticity_token
  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password

  def index
  end

  def auth
    #从session 中取出 user
    permissed=false
    current_user_id = session[CURRENT_USER_ID]
    #记住用户请求的路径,以便登录后自动跳转到用户请求的页面
    session[:go_where] = request.request_uri
    if current_user_id
      # 在user_roles 表中找出 用户所有的 role
      user_role=UserRole.find(:all , :conditions => {:user_id=> session[CURRENT_USER_ID]})
      for ur in user_role
        # 找出每一个角色的权限controller
        permissions = Permisssion.find(:all , :conditions => {:role_id => ur.role_id})
        for p in permissions
          if controller_name  == p.url
            permissed=true
          end
        end
      end

      if permissed
        #go on
      else
        redirect_to "/home/impermission"
      end
    else
      redirect_to :controller=>"/login" ,:action=>"login"
    end
  end
  
  #用户信息完整性判断过滤
  def complete_user_info
    @current_user_id = session[CURRENT_USER_ID]
    if !User.info_completed?(@current_user_id)
      redirect_to(:controller=>"login" , :action=>"update" ,:id => @current_user_id)
    end
  end

  #当前登录的用户
  def current_user
    session[CURRENT_USER_ID] ? User.find(session[CURRENT_USER_ID]) : nil
  end

  def count_by_formula(number, formula)
    #如： count_by_formual(2, "*5") , return => 2*5=10
    eval "#{number}.#{formula[0,1]} #{formula[1, formula.length]}"
  end
 
end
